package com.linkage.usercenter.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linkage.common.base.LocationVo;
import com.linkage.common.base.RequestInfo;
import com.linkage.common.base.RespAppVO;
import com.linkage.common.base.ResponseInfo;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.util.RedisUtils;
import com.linkage.usercenter.config.TokenCheckException;
import com.linkage.usercenter.dao.*;
import com.linkage.usercenter.feign.HomeManageFeign;
import com.linkage.usercenter.pojo.baseDO.PoiBAExcelInfoVO;
import com.linkage.usercenter.pojo.entity.*;
import com.linkage.usercenter.pojo.vo.*;
import com.linkage.usercenter.pojo.vo.managevo.MgDptInfoLineDATA;
import com.linkage.usercenter.pojo.vo.managevo.MgDptInfosLineVO;
import com.linkage.usercenter.service.IuserService;
import com.linkage.usercenter.utils.TableCommonDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserOperationServiceImpl implements IuserService {

    private static final Logger logger = LoggerFactory.getLogger(UserOperationServiceImpl.class);

    @Autowired
    private CoreUserMapper userDao;
    @Autowired
    DptSubInfoMapper dptSubInfoDao;
    @Autowired
    private UserSubInfoMapper userSubInfoDao;

    @Autowired
    private CorePersonInfoMapper personDao;
    @Autowired
    private CoreCardInfoMapper cardDao;
    @Value("${customer.token-config.token-time}")
    private int tokenValidSecond;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HomeManageFeign homeManageFeign;

    @Autowired
    private CoreDptInfoMapper dptInfoDao;

    @Autowired
    private CoreMiddleUserRoleMapper middleUserRoleDao;

    @Autowired
    private CoreMiddleOperateRoleMapper middleOperateRoleDao;
    /* *
     * @describe:  类型描述 注册
     * @author shaofeng.cheng
     * @title register
     * @date 2020/4/19 22:54
     * @param [query, vo]
     * @return void
     * @version: V1.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RequestInfo<RegisterQUERY> query, RegisterVO bussVO) {
        RegisterQUERY reqBuss = query.getBuss();
        this.checkRegisterParam(reqBuss);
        final String userCode = reqBuss.getUserMobile();
        CorePersonInfo personInfo = new CorePersonInfo();
        CoreUser userInfo = new CoreUser();
        userInfo.setUserCode(userCode);
        //入参转DO
        this.dealDataFrom(reqBuss, userInfo, personInfo);
        //添加头像
        String userPhotoUrl = reqBuss.getUserPhotoUrl();
        if (StrUtil.isNotBlank(userPhotoUrl)) {
            UserSubInfo userSubInfoDO = new UserSubInfo();
            userSubInfoDO.setUserCode(userCode);
            userSubInfoDO.setUserPhotoUrl(reqBuss.getUserPhotoUrl());
            userSubInfoDao.insert(userSubInfoDO);
        }
        TableCommonDataUtil.dealCrtUpdTableField(userCode, userInfo, personInfo);
        userDao.insertSelective(userInfo);
        personDao.insertSelective(personInfo);
        bussVO.setUserMobile(userInfo.getUserMobile());
        bussVO.setUserRealName(userInfo.getUserRealName());
    }

    // 手机号 身份证号  checkUpdateParam  校验用户修改入参
    private void checkUpdateParam(UpdateUserInfoQUERY reqBuss, CoreUser userInfoToken) {
        final String userMobile = reqBuss.getUserMobile();
        final String personCardNumber = reqBuss.getPersonCardNumber();

        if (StrUtil.isNotBlank(userMobile) && !StrUtil.equals(userInfoToken.getUserMobile(), userMobile)) {
            throw new ValidateException("手机号不支持修改！");
        }
        if (StrUtil.isBlank(personCardNumber)) {
            return;
        }
        if (!IdcardUtil.isValidCard(personCardNumber)) {
            throw new ValidateException("身份证校验失败！");
        }
        CorePersonInfo personInfo = personDao.getPersonInfoByCardNumber(personCardNumber);
        if (personInfo!= null && !StrUtil.equals(personInfo.getPersonCardNumber(), personCardNumber)) {
            int recordNum = personDao.getRecordNumByCardNumber(personCardNumber);
            if (recordNum > 0) {
                throw new ValidateException("该身份证号已被注册!");
            }
        }
    }

    //校验注册入参
    private void checkRegisterParam(RegisterQUERY reqBuss) {
        final String userMobile = reqBuss.getUserMobile();
        final String personCardNumber = reqBuss.getPersonCardNumber();
        if (StrUtil.hasBlank(userMobile, reqBuss.getUserPassword(),
                reqBuss.getUserRealName(), reqBuss.getPersonClass(), personCardNumber)) {
            throw new ValidateException("必传参数校验不通过！");
        }
        if (!Validator.isMobile(userMobile)) {
            throw new ValidateException("手机号校验失败！");
        }
        if (!IdcardUtil.isValidCard(personCardNumber)) {
            throw new ValidateException("身份证校验失败！");
        }
        int recordNum = userDao.getRecordNumByMobile(userMobile);
        if (recordNum > 0) {
            throw new ValidateException("该手机号已被注册!");
        }
        recordNum = personDao.getRecordNumByCardNumber(personCardNumber);
        if (recordNum > 0) {
            throw new ValidateException("该身份证号已被注册!");
        }
    }


    /* *
     * @describe:  类型描述 获取用户信息
     * @author shaofeng.cheng
     * @title getUserInfo
     * @date 2020/4/20 16:39
     * @param [query, vo]
     * @return void
     * @version: V1.0
     */
    @Override
    public void getUserInfo(RequestInfo<UserInfoQUERY> query, UserInfoVO bussVO) {
        CoreUser userInfoToken = this.getUserInfoByToken(query);
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        if (ObjectUtil.isNull(personInfo)) {
            throw new ValidateException("获取用户人员信息失败!");
        }
        //数据转换
        this.coreDataToUserInfoVO(bussVO, userInfoToken, personInfo);
    }

    /* *
     * @describe:  类型描述 修改用户信息
     * @author shaofeng.cheng
     * @title updateUserInfo
     * @date 2020/4/20 21:18
     * @param [query, vo]
     * @return void
     * @version: V1.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(RequestInfo<UpdateUserInfoQUERY> query, UpdateUserInfoVO bussVO) {
        CoreUser userInfoToken = this.getUserInfoByToken(query);
        UpdateUserInfoQUERY reqBuss = query.getBuss();
        this.checkUpdateParam(reqBuss, userInfoToken);
        CoreUser userInfo = userDao.getRecordByMobile(userInfoToken.getUserMobile());
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        //更新数据
        this.updateUserAndPersonDO(reqBuss, personInfo, userInfo);
        bussVO.setUserMobile(userInfoToken.getUserMobile());
        bussVO.setUserRealName(userInfoToken.getUserRealName());
        //修改token用户信息
        updateUserInfoByToken(query, userInfo);
    }

    /* *
     * @describe:  类型描述  修改用户密码
     * @author shaofeng.cheng
     * @title changePassword
     * @date 2020/4/20 22:55
     * @param [query, vo]
     * @return void
     * @version: V1.0
     */
    @Override
    public void changePassword(RequestInfo<ChangePasswordQUERY> query, ChangePasswordVO bussVO) {
        CoreUser userInfoToken = this.getUserInfoByToken(query);
        ChangePasswordQUERY reqBuss = query.getBuss();
        if (StrUtil.hasBlank(reqBuss.getUserPassword(),
                reqBuss.getOldPassword())) {
            throw new ValidateException("必传参数校验不通过！");
        }
        final String userCode = userInfoToken.getUserCode();
        String oldPassword = reqBuss.getOldPassword();
        List<CoreUser> userInfoList = userDao.getCheckUserInfo(userCode, oldPassword);
        if (ObjectUtil.isNull(userInfoList) || userInfoList.isEmpty()) {
            throw new ValidateException("获取用户信息失败！原始密码错误！");
        }
        if (userInfoList.size() > 1) {
            throw new ValidateException("获取到多个用户信息！");
        }
        CoreUser userInfo = userInfoList.get(0);
        userInfo.setUserPassword(reqBuss.getUserPassword());
        userDao.updatePassword(userInfo);
        bussVO.setUserMobile(userInfo.getUserMobile());
        this.updateUserInfoByToken(query, userInfo);
    }

    //依据TOKEN获取用户信息
    private CoreUser getUserInfoByToken(RequestInfo reqInfo) {
        String usertoken = reqInfo.getBase().getUsertoken();
        if (StrUtil.isNotBlank(usertoken)) {
            try {
                String userInfoTokenString = (String) redisUtils.get(usertoken);
                if (StrUtil.isNotBlank(userInfoTokenString)) {
                    redisUtils.expire(usertoken, tokenValidSecond);
                    return JSONUtil.toBean(userInfoTokenString, CoreUser.class);
                }
            } catch (Exception e) {
                logger.error("redis缓存获取用户信息出错！", e);
                throw new TokenCheckException();
            }
        }
        throw new TokenCheckException();
    }

    //修改token用户信息
    private void updateUserInfoByToken(RequestInfo reqInfo, CoreUser userInfo) {
        String usertoken = reqInfo.getBase().getUsertoken();
        if (StrUtil.isNotBlank(usertoken)) {
            try {
                String personClassType = usertoken.split(":")[2];
                if(StrUtil.equals(CommonSysConstant.PERSON_GLY12_FLAG,personClassType)){
                    logger.info("设置token超时时间为10分钟");
                    redisUtils.set(usertoken, JSONUtil.toJsonStr(userInfo), tokenValidSecond);
                }else{
                    logger.info("设置token超时时间为永久");
                    redisUtils.set(usertoken, JSONUtil.toJsonStr(userInfo));
                }
            } catch (Exception e) {
                logger.error("redis缓存用户信息出错！", e);
                throw new TokenCheckException();
            }
        }
    }


    /* *
     * @describe:  类型描述 管理后台用户登录
     * @author shaofeng.cheng
     * @title login
     * @date 2020/4/21 0:43
     * @param [query, vo]
     * @return void
     * @version: V1.0
     */
    @Override
    public void login(RequestInfo<ExterLoginQUERY> query, ExterLoginVO bussVo) {
        ExterLoginQUERY reqBuss = query.getBuss();
        String userCode = reqBuss.getUserCode();
        if(StrUtil.isBlank(userCode)){
            userCode = reqBuss.getUserMobile();
        }
        String password = reqBuss.getUserPassword();
        if (StrUtil.isBlank(userCode) || StrUtil.isBlank(password) ) {
            throw new ValidateException("必传参数校验不通过！");
        }
//        String userMobile = reqBuss.getUserMobile();
//        List<CoreUser> userInfoList = null;
//        if (StrUtil.isNotBlank(reqBuss.getUserCode()) ) {
            //后台管理用户
//            userInfoList = userDao.getLoginUserInfo(reqBuss.getUserCode(), null, password);
//        }else {
//            //app注册用户
//            userInfoList = userDao.getLoginUserInfo(null, userMobile, password);
//        }
        List<CoreUser> userInfoList = userDao.getLoginUserInfo(userCode, null, password);
        if (ObjectUtil.isNull(userInfoList)|| userInfoList.isEmpty()) {
            throw new ValidateException("登录失败，用户名或密码错误！");
        }
        if (userInfoList.size() > 1) {
            throw new ValidateException("获取到多个用户信息！");
        }
        CoreUser userInfo = userInfoList.get(0);


        if(CommonSysConstant.CODE_ZERO.equals(userInfo.getUserStatus())){
            throw new ValidateException("该用户已被锁定，请联系管理员！");
        }
        if(!CommonSysConstant.CODE_ZERO.equals(userInfo.getUserJobFlag())){
            throw new ValidateException("该用户未审核通过！");
        }

        if("1".equals(userInfo.getUserDelFlag())){
            throw new ValidateException("该用户信息已被删除，请联系管理员！");
        }
        UserSubInfo userSubInfo = userSubInfoDao.selectByPrimaryKey(userInfo.getUserCode());
        if(userSubInfo!=null && userSubInfo.getUserExpireTime()!=null
                &&  DateUtil.compare(new Date(), userSubInfo.getUserExpireTime()) > 0 ){
//            用户到期时间  锁定用户
            userInfo.setUserStatus(CommonSysConstant.CODE_ZERO);
            TableCommonDataUtil.dealCrtUpdTableField(userInfo.getUserCode(), userInfo);
            userDao.updateByPrimaryKeySelective(userInfo);
            throw new ValidateException("该用户已过期，请联系管理员！");
        }
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfo.getUserPersonCode());
        if (ObjectUtil.isNull(personInfo)) {
            throw new ValidateException("获取人员信息失败！");
        }

        if(!CommonSysConstant.CODE_ZERO.equals(personInfo.getPersonJobFlag())){
            throw new ValidateException("该用户未审核通过！");
        }
        if(StrUtil.equals("0",bussVo.getFrom())){
            //        管理后台  人员类别 (0群众 1保安 2警察,3超级管理员 4. 一级管理员  5.二级管理员 6 自建人员 9 运营商  )
//            if("3,4,5,9".contains(personInfo.getPersonClass())){
//                throw new ValidateException("该用户仅可登录后台管理系统！");
//            }
        }else{
            if(!"3,4,5,9".contains(personInfo.getPersonClass())){
                throw new ValidateException("该用户无管理后台登录权限！");
            }
        }
        List<CoreMiddleUserRole> middleUserRoleDOList =  middleUserRoleDao.selectByUserCode(userCode);
        String roleCode = CollUtil.isEmpty(middleUserRoleDOList) ? "" : middleUserRoleDOList.get(0).getMiddleRoleCode();
        String usertoken = this.genUserTokenKey(query, userInfo, personInfo);
        query.getBase().setUsertoken(usertoken);
        this.updateUserInfoByToken(query, userInfo);
        bussVo.setUsertoken(usertoken);
        bussVo.setUserMobile(userInfo.getUserMobile());
        bussVo.setUserRealName(userInfo.getUserRealName());
        bussVo.setUserCode(userInfo.getUserCode());
        bussVo.setPersonClass(personInfo.getPersonClass());
        bussVo.setAddress(personInfo.getPersonLiveAddress());
        bussVo.setRoleCode(roleCode);
        if(StrUtil.isNotBlank(roleCode)){
            List<Map<String,String>> operCodeList = middleOperateRoleDao.queryOperCodeListByRoleCode(roleCode);
            bussVo.setOperCodeList(operCodeList);
        }

    }

    @Override
    public void queryDptsLine(RequestInfo<Map<String, String>> query, MgDptInfosLineVO vo) {
        String orgCode = query.getBuss().get("paramVar");
        List<MgDptInfoLineDATA> resultList = new ArrayList<MgDptInfoLineDATA>();
        List<CoreDptInfo> dptlist = dptInfoDao.queryByOrgCodeAndLevel(CommonSysConstant.ORG_CODE_POLICE);
        if( dptlist != null || !dptlist.isEmpty()){
            for (CoreDptInfo coreDptInfo : dptlist) {
                MgDptInfoLineDATA dptDATA = new MgDptInfoLineDATA();
                dptDATA.setDptCode(coreDptInfo.getDptCode());
                dptDATA.setDptName(coreDptInfo.getDptName());
                String dptUserkeyToken = "TOKEN:"+coreDptInfo.getDptCode().trim()+":"+CommonSysConstant.PERSON_GLY12_FLAG+":*";
                dptDATA.setLineFlag(redisUtils.keysAndExsit(dptUserkeyToken) ? "1":"0");
                resultList.add(dptDATA);
            }
        }
        vo.setDptLineInfos(resultList);
    }

    @Override
    public void checkMobile(String bolile) {
        if (!Validator.isMobile(bolile)) {
            throw new ValidateException("手机号校验不通过，请填写正确的手机号!");
        }
        int userNum = userDao.getRecordNumByMobile(bolile);
        if(userNum>0){
            throw new ValidateException("该手机号已被注册!");
        }

    }

    //后台添加保安信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserForSecurity(RequestInfo<MgUserSecurityQUERY> query, CoreUser userInfoToken) {
        String userCurrentCode = userInfoToken.getUserCode();
        MgUserSecurityQUERY requestInfo = query.getBuss();
        if(StrUtil.hasBlank(requestInfo.getUserMobile(), requestInfo.getUserPassword(), requestInfo.getUserRealName())){
            throw new ValidateException("参数不完整!");
        }
        String userCode = requestInfo.getUserMobile();
        String userMobile = requestInfo.getUserMobile();
        String userName = requestInfo.getUserRealName();
        this.checkMobileIsExist(userMobile);
        CorePersonInfo personInfo = new CorePersonInfo();
        CoreUser userInfo = new CoreUser();
        userInfo.setUserCode(userCode);
        userInfo.setUserPersonCode(userCode);
        userInfo.setUserPassword(requestInfo.getUserPassword());
        userInfo.setUserRealName(userName);
        userInfo.setUserDisplayName(userName);
        userInfo.setUserMobile(userMobile);
        userInfo.setUserDelFlag(CommonSysConstant.CODE_ZERO);
        userInfo.setUserJobFlag(CommonSysConstant.CODE_ZERO);
        userInfo.setUserStatus(CommonSysConstant.CODE_ONE);
        personInfo.setPersonCode(userCode);
        personInfo.setPersonRealName(userName);
        personInfo.setPersonMobile(userMobile);
        personInfo.setPersonOldName(userName);
        personInfo.setPersonDelFlag(CommonSysConstant.CODE_ZERO);
        personInfo.setPersonJobFlag(CommonSysConstant.CODE_ZERO);
        personInfo.setPersonStatus(CommonSysConstant.CODE_ONE);
        personInfo.setPersonClass(CommonSysConstant.PERSON_CLASS_ONE);
        TableCommonDataUtil.dealCrtUpdTableField(userCurrentCode, userInfo, personInfo);
        userDao.insert(userInfo);
        personDao.insert(personInfo);
    }
    private void checkMobileIsExist(String userMobile){
        if(StrUtil.isBlank(userMobile)){
            throw new ValidateException("手机号不能为空！");
        }
        if (!Validator.isMobile(userMobile)) {
            throw new ValidateException("手机号校验失败，格式不正确！");
        }
        int recordNum = userDao.getRecordNumByMobile(userMobile);
        if (recordNum > 0) {
            throw new ValidateException("该手机号已被注册!");
        }
    }

    /**
     *  查询部门/企业信息一级管理员信息
     * @param query
     * @param userInfoToken
     * @return
     */
    @Override
    public MgUserManageQUERY queryManageLevelOne(RequestInfo<MgUserManageQUERY> query, CoreUser userInfoToken) {
        MgUserManageQUERY userManageVO = new MgUserManageQUERY();
        MgUserManageQUERY requestInfo = query.getBuss();
        String dptCode = requestInfo.getDptCode();
        if (StrUtil.isBlank(dptCode)) {
            throw new ValidateException("参数不完整!");
        }
        List<CoreDptInfo> dptInfoList = dptInfoDao.queryByDptCode(dptCode);
        if (CollUtil.isEmpty(dptInfoList)) {
            throw new ValidateException("查询机构信息失败，请检查机构代码是否正确！");
        }
        CoreDptInfo dptInfo = dptInfoList.get(0);
        List<CoreUser> userInfoList = userDao.selectGLYOneByDptCode(dptCode);
        if (CollUtil.isEmpty(userInfoList)) {
            throw new ValidateException("查询一级管理员失败！");
        }
        CoreUser userInfoGLYOne = userInfoList.get(0);
        userManageVO.setDptCode(dptInfo.getDptCode());
        userManageVO.setDptName(dptInfo.getDptName());
        userManageVO.setDptParentCode(dptInfo.getDptParentCode());
        userManageVO.setUserCode(userInfoGLYOne.getUserCode());
        userManageVO.setUserRealName(userInfoGLYOne.getUserRealName());
        userManageVO.setUserMobile(userInfoGLYOne.getUserMobile());
        userManageVO.setDptFlag(CommonSysConstant.CODE_ONE);
        userManageVO.setUserPassword(userInfoGLYOne.getUserPassword());
        if (CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfo.getDptOrgCode())) {
            DptSubInfo dptSubInfo = dptSubInfoDao.selectByPrimaryKey(dptCode);
            if(dptSubInfo != null){
                userManageVO.setComParentCode(dptSubInfo.getEnterpriseOrgId());
            }
            userManageVO.setDptFlag(CommonSysConstant.CODE_ZERO);
        }
        List<CoreMiddleUserRole> recordList = middleUserRoleDao.selectByUserCode(userInfoGLYOne.getUserCode());
        if (CollUtil.isNotEmpty(recordList)) {
            userManageVO.setRoleCode(recordList.get(0).getMiddleRoleCode());
        }
        return userManageVO;
    }
    //调度台设置， 部门/企业信息一级管理员信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addManageLevelOne(RequestInfo<MgUserManageQUERY> query, CoreUser userInfoToken) {
        MgUserManageQUERY requestInfo = query.getBuss();
        String userCode = requestInfo.getUserCode();
        ////修改标志   1 修改 ； 2  删除 ； 其它 新增
        if("2".equals(requestInfo.getUpdateFlag())){
            String dptCode = requestInfo.getDptCode();
            if(StrUtil.isBlank(dptCode)){
                throw new ValidateException("参数不完整!");
            }
//            CorePersonInfo personInfoUser = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
//            if (personInfoUser == null) {
//                throw new ValidateException("获取登录用户信息失败！");
//            }
//            if (!CommonSysConstant.PERSON_CLASS_THREE.equals(personInfoUser.getPersonClass())) {
//                throw new ValidateException("只有超级管理员才可以删除！");
//            }
            List<CoreDptInfo> dptInfoList = dptInfoDao.queryByDptCode(dptCode);
            if(CollUtil.isEmpty(dptInfoList)){
                throw new ValidateException("查询机构信息失败，请检查机构代码是否正确！");
            }
            CoreDptInfo dptInfo = dptInfoList.get(0);
            if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfo.getDptOrgCode()) || CommonSysConstant.ORG_CODE_TYPE_6.equals(dptInfo.getDptOrgCode())){
                List<CoreDptInfo> dptDOList = CollUtil.newArrayList();
                this.getDptComList(dptCode, dptDOList);
                if(CollUtil.isNotEmpty(dptDOList)){
                    throw new ValidateException("该公司存在子公司，请先删除子公司信息！");
                }
                dptSubInfoDao.deleteByPrimaryKey(dptCode);
            }else {
                List<CoreDptInfo> dptDOList = this.getDptListAll(dptCode);
                if(CollUtil.isNotEmpty(dptDOList)){
                    throw new ValidateException("该部门存在下级部门 ，请先删除下级部门信息！");
                }
            }
            dptInfoDao.deleteByPrimaryKey(dptInfo.getId());
            userDao.deleteByDptCode(dptCode);
            personDao.deleteByDptCode(dptCode);
            middleUserRoleDao.deleteByDptCode(dptCode);
        } else if("1".equals(requestInfo.getUpdateFlag())){
            String dptcode = requestInfo.getDptCode();
            if(StrUtil.hasBlank(userCode, dptcode)){
                throw new ValidateException("参数不完整!");
            }
//            CorePersonInfo personInfoUser = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
//            if (personInfoUser == null) {
//                throw new ValidateException("获取登录用户信息失败！");
//            }
//            if (!CommonSysConstant.PERSON_CLASS_THREE.equals(personInfoUser.getPersonClass())) {
//                throw new ValidateException("只有超级管理员才可以修改！");
//            }
            CoreUser userInfo = userDao.selectByUserCode(userCode);
            CorePersonInfo personInfo = personDao.getRecordByUserCode(userCode);
            List<CoreDptInfo> dptInfoList = dptInfoDao.queryByDptCode(dptcode);
            if(userInfo == null || personInfo == null){
                throw new ValidateException("查询人员信息失败，请检查账号是否正确！");
            }
            if(CollUtil.isEmpty(dptInfoList)){
                throw new ValidateException("查询机构信息失败，请检查机构代码是否正确！");
            }
            String userMobile = requestInfo.getUserMobile();
            if(StrUtil.isNotBlank(userMobile) && !userMobile.equals(userInfo.getUserMobile()) ){
                userInfo.setUserMobile(userMobile);
                personInfo.setPersonMobile(userMobile);
            }
            String userName = requestInfo.getUserRealName();
            if(StrUtil.isNotBlank(userName) && !userName.equals(userInfo.getUserRealName()) ){
                userInfo.setUserRealName(userName);
                userInfo.setUserDisplayName(userName);
                personInfo.setPersonRealName(userName);
                personInfo.setPersonOldName(userName);
            }
            if(StrUtil.isNotBlank(requestInfo.getUserPassword())){
                userInfo.setUserPassword(requestInfo.getUserPassword());
            }
            CoreDptInfo dptInfo = dptInfoList.get(0);
            String dptName = requestInfo.getDptName() ;
            if(StrUtil.isNotBlank(dptName) && !dptName.equals(dptInfo.getDptName()) ){
                dptInfo.setDptName(dptName);
            }
            if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfo.getDptOrgCode()) || CommonSysConstant.ORG_CODE_TYPE_6.equals(dptInfo.getDptOrgCode())){
                //企业
                String dptParentCode = requestInfo.getDptParentCode();
                //上级部门代码
                List<CoreDptInfo> dptParentInfoList = dptInfoDao.queryByDptCode(dptParentCode);
                if(CollUtil.isEmpty(dptParentInfoList) ){
                    throw new ValidateException("上级部门代码不存在! --"+dptParentCode);
                }
                dptInfo.setDptParentCode(requestInfo.getDptParentCode());
                //归属总公司代码
                String comParentCode =  requestInfo.getComParentCode();
                if(StrUtil.isNotBlank(comParentCode) ){
                    List<CoreDptInfo> dptInfoDOList = dptInfoDao.queryByDptCode(comParentCode);
                    if(CollUtil.isEmpty(dptInfoDOList) ){
                        throw new ValidateException("归属总公司代码不存在! --"+comParentCode);
                    }
                    DptSubInfo dptSubInfo = dptSubInfoDao.selectByPrimaryKey(dptcode);
                    if(dptSubInfo == null ){
                        dptSubInfo = new  DptSubInfo();
                        dptInfo.setDptLevel(dptInfoDOList.get(0).getDptLevel()+1);
                        //是否总公司，0-是，1-不是
                        dptSubInfo.setIsHeadDpt(CommonSysConstant.CODE_ONE);
                        dptSubInfo.setEnterpriseOrgId(comParentCode);
                        dptSubInfo.setAuditStatus(CommonSysConstant.CODE_ONE);
                        dptSubInfo.setDptHeadPhone(userMobile);
                        dptSubInfo.setDptHead(userInfo.getUserRealName());
                        dptSubInfoDao.insert(dptSubInfo);
                    }else if(!comParentCode.equals(dptSubInfo.getEnterpriseOrgId())){
                        dptInfo.setDptLevel(dptInfoDOList.get(0).getDptLevel()+1);
                        //是否总公司，0-是，1-不是
                        dptSubInfo.setIsHeadDpt(CommonSysConstant.CODE_ONE);
                        dptSubInfo.setEnterpriseOrgId(comParentCode);
                        dptSubInfoDao.updateByPrimaryKey(dptSubInfo);
                    }
                }
            }else {
                String dptParentCode = requestInfo.getDptParentCode();
                if(StrUtil.isNotBlank(dptParentCode) && !dptParentCode.equals(dptInfo.getDptParentCode())){
                    List<CoreDptInfo> dptParentInfoList = dptInfoDao.queryByDptCode(dptParentCode);
                    if(CollUtil.isEmpty(dptParentInfoList) ){
                        throw new ValidateException("上级部门代码不存在! --"+dptParentCode);
                    }
                    dptInfo.setDptParentCode(dptParentCode);
                    dptInfo.setDptLevel(dptParentInfoList.get(0).getDptLevel()+1);
                }
            }
            TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(),
                    userInfo, personInfo, dptInfo);
            userDao.updateByPrimaryKeySelective(userInfo);
            personDao.updateByPrimaryKeySelective(personInfo);
            dptInfoDao.updateByPrimaryKeySelective(dptInfo);
            if(StrUtil.isNotBlank(requestInfo.getRoleCode())){
                middleUserRoleDao.deleteByUserCode(userCode);
                CoreMiddleUserRole record = new CoreMiddleUserRole();
                record.setMiddleUserCode(userCode);
                record.setMiddleRoleCode(requestInfo.getRoleCode());
                middleUserRoleDao.insert(record);
            }
        }else{
            if(StrUtil.hasBlank(userCode, requestInfo.getUserMobile(),requestInfo.getDptFlag(),
                    requestInfo.getDptName(),
                    requestInfo.getUserRealName(), requestInfo.getUserPassword())){
                throw new ValidateException("参数不完整!");
            }
//            CorePersonInfo personInfoUser = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
//            if (personInfoUser == null) {
//                throw new ValidateException("获取登录用户信息失败！");
//            }
//            if (!CommonSysConstant.PERSON_CLASS_THREE.equals(personInfoUser.getPersonClass())) {
//                throw new ValidateException("只有超级管理员才可以添加一级管理员！");
//            }
            String userMobile = requestInfo.getUserMobile();
            String userName = requestInfo.getUserRealName();
            this.checkMobileIsExist(userMobile);
            CorePersonInfo personInfo = new CorePersonInfo();
            CoreUser userInfo = new CoreUser();
            userInfo.setUserCode(userCode);
            userInfo.setUserMobile(userMobile);
            userInfo.setUserPersonCode(userCode);
            userInfo.setUserPassword(requestInfo.getUserPassword());
            userInfo.setUserRealName(userName);
            userInfo.setUserDisplayName(userName);
            userInfo.setUserDelFlag(CommonSysConstant.CODE_ZERO);
            userInfo.setUserJobFlag(CommonSysConstant.CODE_ZERO);
            userInfo.setUserStatus(CommonSysConstant.CODE_ONE);
            personInfo.setPersonCode(userCode);
            personInfo.setPersonMobile(userMobile);
            personInfo.setPersonRealName(userName);
            personInfo.setPersonOldName(userName);
            personInfo.setPersonDelFlag(CommonSysConstant.CODE_ZERO);
            personInfo.setPersonJobFlag(CommonSysConstant.CODE_ZERO);
            personInfo.setPersonStatus(CommonSysConstant.CODE_ONE);
            personInfo.setPersonClass(CommonSysConstant.PERSON_CLASS_FOUR);
            if(CommonSysConstant.CODE_SIX.equals(requestInfo.getDptFlag())){
                personInfo.setPersonClass(CommonSysConstant.PERSON_CLASS_SIX);
            }
            CoreDptInfo dptInfo = new CoreDptInfo();
            if(CommonSysConstant.CODE_ONE.equals(requestInfo.getDptFlag())){
                //部门
                String dptCode = "";
                //无上级部门为  1级部门

                if(StrUtil.isBlank(requestInfo.getDptParentCode())){
                    dptCode = this.genDptCodeByParentCode("", true);
                    dptInfo.setDptLevel(1);
                }else{
                    String dptParentCode = requestInfo.getDptParentCode();
                    List<CoreDptInfo> dptParentInfoList = dptInfoDao.queryByDptCode(dptParentCode);
                    if(CollUtil.isEmpty(dptParentInfoList) ){
                        throw new ValidateException("上级部门代码不存在! --"+dptParentCode);
                    }
                    CoreDptInfo dptParentInfo = dptParentInfoList.get(0);
                    dptCode = this.genDptCodeByParentCode(requestInfo.getDptParentCode(), true);
                    dptInfo.setDptParentCode(requestInfo.getDptParentCode());
                    dptInfo.setDptLevel(dptParentInfo.getDptLevel()+1);
                }
                dptInfo.setDptCode(dptCode);
                dptInfo.setDptOrgCode(CommonSysConstant.ORG_CODE_POLICE);
                dptInfo.setDptName(requestInfo.getDptName());
            }else {
                //企业
                DptSubInfo dptSubInfo = new DptSubInfo();
                String dptCode = "";
                if(StrUtil.isBlank(requestInfo.getDptParentCode())){
                    dptCode = this.genDptCodeByParentCode("", false);
                }else{
                    dptCode = this.genDptCodeByParentCode(requestInfo.getDptParentCode(), false);
                    String dptParentCode = requestInfo.getDptParentCode();
                    List<CoreDptInfo> dptParentInfoList = dptInfoDao.queryByDptCode(dptParentCode);
                    if(CollUtil.isEmpty(dptParentInfoList) ){
                        throw new ValidateException("上级部门代码不存在! --"+dptParentCode);
                    }
                    dptInfo.setDptParentCode(requestInfo.getDptParentCode());
                }
                String comParentCode =  requestInfo.getComParentCode();
                if(StrUtil.isBlank(comParentCode)){
                    //是否总公司，0-是，1-不是
                    dptSubInfo.setIsHeadDpt(CommonSysConstant.CODE_ZERO);
                    dptInfo.setDptLevel(1);
                }else {
                    List<CoreDptInfo> dptInfoDOList = dptInfoDao.queryByDptCode(comParentCode);
                    if(CollUtil.isEmpty(dptInfoDOList)){
                        throw new ValidateException("归属总公司代码不存在! --"+comParentCode);
                    }
                    dptSubInfo.setIsHeadDpt(CommonSysConstant.CODE_ONE);
                    dptSubInfo.setEnterpriseOrgId(requestInfo.getComParentCode());
                    dptInfo.setDptLevel(dptInfoDOList.get(0).getDptLevel()+1);

                }
                dptInfo.setDptCode(dptCode);
                dptInfo.setDptName(requestInfo.getDptName());
                dptInfo.setDptOrgCode(CommonSysConstant.ORG_CODE_TYPE_5);
                if(CommonSysConstant.CODE_SIX.equals(requestInfo.getDptFlag())){
                    dptInfo.setDptOrgCode(CommonSysConstant.ORG_CODE_TYPE_6);
                }

                //审核状态，0-未处理，1-已通过，2-已拒绝
                dptSubInfo.setAuditStatus(CommonSysConstant.CODE_ONE);
                dptSubInfo.setDptHeadPhone(userMobile);
                dptSubInfo.setDptHead(userInfo.getUserRealName());
                dptSubInfo.setDptCode(dptCode);
                int dptExistNum =  dptSubInfoDao.selectRecordNumByDptCode(dptCode);
                if(dptExistNum>0){
                    dptSubInfoDao.updateByPrimaryKey(dptSubInfo);
                }else{
                    dptSubInfoDao.insert(dptSubInfo);

                }
            }
            dptInfo.setDptStatus(CommonSysConstant.CODE_ONE);
            personInfo.setPersonOrgCode(dptInfo.getDptCode());
            personInfo.setPersonOrgName(dptInfo.getDptName());
            if(StrUtil.isNotBlank(requestInfo.getRoleCode())){
                CoreMiddleUserRole record = new CoreMiddleUserRole();
                record.setMiddleUserCode(userCode);
                record.setMiddleRoleCode(requestInfo.getRoleCode());
                middleUserRoleDao.insert(record);
            }
            TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(), userInfo, personInfo, dptInfo);
            userDao.insert(userInfo);
            personDao.insert(personInfo);
            dptInfoDao.insert(dptInfo);
        }



    }

    @Override
    public List<DptParentVO> queryManageParentDpt(String dptType) {
        List<DptParentVO> resultList;
        if(CommonSysConstant.CODE_ONE.equals(dptType)){
            resultList = dptInfoDao.getDptDicByDptType();
        }else{
            resultList = dptInfoDao.getDptDicByDptTypeForCom();
        }
        return resultList;
    }

    //生成部门代码
    private String genDptCodeByParentCode(String parentCode, boolean dptCodeFlag) {
        StringBuilder dptCodeStrBuil = new StringBuilder();
        String dptCode = "";
        if(StrUtil.isBlank(parentCode)){
            dptCodeStrBuil.append("ORG-");
            if(dptCodeFlag){
                dptCodeStrBuil.append("DPT-");
            }else {
                dptCodeStrBuil.append("COM-");
            }
            dptCodeStrBuil.append(RandomUtil.randomInt(11111,99999));
            dptCode = dptCodeStrBuil.toString();
        }else{
            dptCodeStrBuil.append(parentCode+"-");
            dptCodeStrBuil.append(RandomUtil.randomInt(1111,9999));
            dptCode = dptCodeStrBuil.toString();
        }

        int dptExistNum =  dptInfoDao.selectRecordNumByDptCode(dptCode);
        if(dptExistNum>0){
            dptCode = this.genDptCodeByParentCode(parentCode, dptCodeFlag);
        }
        return dptCode;
    }

    @Override
    public Map statisticsBA(String token){
        // token
        String dptCode = token.split(":")[1];
        if(StrUtil.equals("CJGLY-3",token.split(":")[2])){
            dptCode = "POLICE-0001";
        }
        //添加本部门
        CoreDptInfo dptInfo = dptInfoDao.queryByDptCode(dptCode).get(0);
        List<CoreDptInfo> coreDptInfos = new ArrayList<CoreDptInfo>();
        if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfo.getDptOrgCode())){
            //企业特殊处理
            this.getDptComList(dptInfo.getDptCode(), coreDptInfos);
        }else{
            coreDptInfos = getDptListAll(dptCode);
        }
        coreDptInfos.add(dptInfo);
        //保险公司列表
        List<CoreDptInfo> shDptList =  coreDptInfos.stream().filter(x -> StrUtil.equals("ORG-009",x.getDptOrgCode())).collect(Collectors.toList());
        //保险公司列表
        List<CoreDptInfo> qyDptList =  coreDptInfos.stream().filter(x -> StrUtil.equals("ORG-005",x.getDptOrgCode())).collect(Collectors.toList());
        qyDptList.addAll(shDptList);
        //TODO 循环部门列表，获取用户信息
        //未持证保安在线
        int noHoldOnline = 0;
        //保安在线
        int baOnline = 0;
        //保安总数
        int baTotal = 0;
        //未持证保安总数
        int noHoldTotal = 0;
        //散户总数
        int shTotal = 0;
        //散户在线
        int shOnline = 0;
        //统计保安
        for(CoreDptInfo dptInfo1 : qyDptList){
            List<CorePersonInfo> userList = personDao.getRecordByDptCode(dptInfo1.getDptCode(),null);
            for (CorePersonInfo person : userList){
                if(StrUtil.equals("1",person.getPersonClass())){
                    baTotal ++;
                    //判断在线
                    String location = queryNewestLocation(person.getPersonCode(),person.getPersonOrgCode());
                    if(StrUtil.isNotEmpty(location)){
                        //如果有位置信息，重新判断在线状态
                        LocationVo locationVo = com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(location),LocationVo.class);
                        long restTime = System.currentTimeMillis() - locationVo.getTimestamp();
                        if(restTime <= 60000){
                            baOnline++;
                            if(StrUtil.equals("0",person.getPersonSecurityFlag())){
                                noHoldOnline++;
                            }
                            if(StrUtil.equals("UNKNOW-DPT",dptInfo1.getDptCode())){
                                shOnline++;
                            }
                        }
                    }
                    if(StrUtil.equals("0",person.getPersonSecurityFlag()) ){
                        noHoldTotal++;
                    }
                    if(StrUtil.equals("UNKNOW-DPT",dptInfo1.getDptCode())){
                        shTotal++;
                    }
                }
            }
        }
        return MapUtil.builder().put("sanhOnlind",shOnline).put("sanhOffline",shTotal-shOnline)
                .put("noHoldOnline",noHoldOnline).put("noHoldOffline",noHoldTotal-noHoldOnline)
                .put("baOnline",baOnline).put("baOffline",baTotal-baOnline)
                .put("baTotal",baTotal).put("noHoldTotal",noHoldTotal).put("sanhTotal",shTotal).build();
    }

    //根据机构代码查询机构信息
    private void getDptComList(String dptCode, List<CoreDptInfo> coreDptInfos) {
        if(StrUtil.isBlank(dptCode)){
            return;
        }
        List<String>  dptCodeList = dptSubInfoDao.queryCodebyParentCode(dptCode);
        if(dptCodeList == null || dptCodeList.isEmpty()){
            return;
        }
        List<CoreDptInfo>  dptDOList = dptInfoDao.queryByCodeList(dptCodeList);
        if(dptDOList == null || dptDOList.isEmpty()){
            return;
        }
        coreDptInfos.addAll(dptDOList);
        for (CoreDptInfo dptDO : dptDOList) {
            this.getDptComList(dptDO.getDptCode(), coreDptInfos);
        }
    }

    /**
     * 查询子机构
     * @param dptCode
     * @return
     */
    private List<CoreDptInfo> getDptListAll(String dptCode){
        List<CoreDptInfo> result = new ArrayList<>();
        List<CoreDptInfo> list = dptInfoDao.queryByParentCode(dptCode);
        if(ObjectUtil.isNotEmpty(list)){
            result.addAll(list);
            for(CoreDptInfo dptInfo : list){
                result.addAll(getDptListAll(dptInfo.getDptCode()));
            }
        }
        return result;
    }

    @Override
    public Map statisticsJC(String dptCode,String token){
        if(StrUtil.equals("CJGLY-3",token.split(":")[2])){
            dptCode = "POLICE-0001";
        }
        if(StrUtil.isEmpty(dptCode)){
            dptCode = token.split(":")[1];
        }
        //查询本部门
        CoreDptInfo dptInfo = dptInfoDao.queryByDptCode(dptCode).get(0);
        List<CoreDptInfo> coreDptInfos = new ArrayList<CoreDptInfo>();
        if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfo.getDptOrgCode())){
            //企业特殊处理
            this.getDptComList(dptInfo.getDptCode(), coreDptInfos);
        }else {
            coreDptInfos = getDptListAll(dptCode);
        }
        coreDptInfos.add(dptInfo);
        int qyonline = 0;
        int qytotal = 0;
        int jcTotal = 0;
        int jcOnline = 0;
        for(CoreDptInfo dptInfo1 : coreDptInfos) {
            if (StrUtil.equals(CommonSysConstant.ORG_CODE_POLICE, dptInfo1.getDptOrgCode())) {
                List<CorePersonInfo> personList = personDao.getRecordByDptCode(dptInfo1.getDptCode(),null);
                for (CorePersonInfo person : personList) {
                    if (StrUtil.equals(CommonSysConstant.PERSON_CLASS_FOUR, person.getPersonClass()) || StrUtil.equals(CommonSysConstant.PERSON_CLASS_FIVE, person.getPersonClass())) {
                        jcTotal++;
                        Set<String> keys = redisUtils.keys(CommonSysConstant.PERSON_TOKEN + CommonSysConstant.PERSON_TOKEN_SEP_CHAR + dptInfo1.getDptCode() +
                                CommonSysConstant.PERSON_TOKEN_SEP_CHAR + CommonSysConstant.PERSON_GLY12_FLAG + CommonSysConstant.PERSON_TOKEN_SEP_CHAR + person.getPersonCode());
                        if (null != keys && keys.size() > 0) {
                            jcOnline++;
                        }
                    }
                }
            } else if (StrUtil.equals(CommonSysConstant.ORG_CODE_TYPE_5, dptInfo1.getDptOrgCode())) {
                List<CorePersonInfo> personList = personDao.getRecordByDptCode(dptInfo1.getDptCode(),null);
                for (CorePersonInfo person : personList) {
                    if (StrUtil.equals(CommonSysConstant.PERSON_CLASS_FOUR, person.getPersonClass()) || StrUtil.equals(CommonSysConstant.PERSON_CLASS_FIVE, person.getPersonClass())) {
                        qytotal++;
                        Set<String> keys = redisUtils.keys(CommonSysConstant.PERSON_TOKEN + CommonSysConstant.PERSON_TOKEN_SEP_CHAR + dptInfo1.getDptCode() +
                                CommonSysConstant.PERSON_TOKEN_SEP_CHAR + CommonSysConstant.PERSON_GLY12_FLAG + CommonSysConstant.PERSON_TOKEN_SEP_CHAR + person.getPersonCode());
                        if (null != keys && keys.size() > 0) {
                            qyonline++;
                        }
                    }
                }
            }
        }
        return MapUtil.builder().put("jcOnline",jcOnline).put("jcTotal",jcTotal)
                .put("qyonline",qyonline).put("qytotal",qytotal).build();
    }

    @Override
    public  PageInfo<UserInfoListVO> getUserInfoList(RequestInfo<UserInfoListQUERY> query) {
        if(query.getBuss() == null){
            throw new ValidateException("入参不能为空!");
        }
        /**
         * 人员类别 (0群众 1保安 2警察,3超级管理员 4. 一级管理员  5.二级管理员)
         */
         String reqUserMobile = query.getBuss().getUserMobile();
         String reqPersonClass = query.getBuss().getPersonClass();
         String personClass = StrUtil.isNotBlank(reqPersonClass) ? reqPersonClass : CommonSysConstant.PERSON_CLASS_ONE;
        Integer page = StrUtil.isEmpty(query.getBase().getPageNum())?0:Integer.parseInt(query.getBase().getPageNum());
        Integer pageSize = StrUtil.isEmpty(query.getBase().getPageRows())?10:Integer.parseInt(query.getBase().getPageRows());
        PageHelper.startPage(page,pageSize);
        List<UserInfoListVO> voList = userDao.queryUserInfoListVOs(reqUserMobile, personClass);
        PageInfo<UserInfoListVO> pageInfo = new PageInfo<UserInfoListVO>(voList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePersonInfo(RequestInfo<UpdateUserQUERY> query) {
        UpdateUserQUERY reqBuss = query.getBuss();
        if(reqBuss == null || StrUtil.isBlank(reqBuss.getUserCode())){
            throw new ValidateException("入参用户编码不能为空!");
        }
        String userCode = reqBuss.getUserCode();
        CoreUser userInfo =  userDao.getRecordByUserCode(userCode, null);
        if(ObjectUtil.isNull(userInfo)){
            throw new ValidateException("查询用户信息失败！");
        }
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfo.getUserPersonCode());
        this.updateUserAndPersonDO(reqBuss, personInfo, userInfo);
        TableCommonDataUtil.dealCrtUpdTableField(userCode, personInfo, userInfo );
        userDao.updateByPrimaryKey(userInfo);
        personDao.updateByPrimaryKey(personInfo);
    }

    @Override
    public ResponseInfo forgetPwd(ChangePasswordQUERY query){
        //根据手机号查询用户是否存在
        List<CoreUser> userList = userDao.getAllRecordByUserCode(query.getPhone());
        if(CollUtil.isEmpty(userList)){
            return ResponseInfo.error("当前用户不存在！");
        }
        CoreUser user = userList.get(0);
        String verifiCode = String.valueOf(redisUtils.get("verifiCode:"+query.getPhone()));
        if(StrUtil.isEmpty(verifiCode)){
            return ResponseInfo.error("验证码已过期！");
        }
        if(!StrUtil.equals(verifiCode,query.getVerifiCode())){
            return ResponseInfo.error("验证码输入错误！");
        }
        user.setUserPassword(query.getUserPassword());
        userDao.updatePassword(user);
        return ResponseInfo.success("密码重置成功！");
    }

    //导入保安信息,启用账号 批量审核通过
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userExcel(List<PoiBAExcelInfoVO> requestList, List<Map> list) {

        Long nowDateLong = System.currentTimeMillis();
        if(CollUtil.isEmpty(requestList)){
            return;
        }
        String msg = null;
        for (PoiBAExcelInfoVO userInfoVO : requestList) {
            if(ObjectUtil.isNull(userInfoVO)){
                continue;
            }
            String userCode = userInfoVO.getUserCode();
            String userMobile = userInfoVO.getUserMobile();
            String userExpireTimeLongDay = userInfoVO.getUserExpireTimeLongDay();
            Map userMap = new HashMap();
            list.add(userMap);
            userMap.put("userCode", userInfoVO.getUserCode());
            userMap.put("userMobile", userMobile);


            if(StrUtil.isBlank(userCode)){
                msg = "登陆账号不能为空！";
                userMap.put("msg",msg);
                continue;
            }
            if(StrUtil.isBlank(userMobile)){
                msg = "手机号不能为空！";
                userMap.put("msg",msg);
                continue;
            }

            if (!Validator.isMobile(userMobile)) {
                msg = "手机号校验失败，格式不正确！";
                userMap.put("msg",msg);
                continue;
            }
            CoreUser userDO = userDao.getRecordByUserCode(userCode, userMobile);
            if (ObjectUtil.isNull(userDO)) {
                msg = "账号不存在！";
                userMap.put("msg",msg);
                continue;
            }

            CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(userDO.getUserPersonCode());

            UserSubInfo subInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
//            是否在职（0：正常-审核通过；1：离职-审核拒绝,2：初始化  ）
            userDO.setUserJobFlag(CommonSysConstant.CODE_ZERO);
            userDO.setUserStatus(CommonSysConstant.CODE_ONE);
            personInfoDO.setPersonJobFlag(CommonSysConstant.CODE_ZERO);
            personInfoDO.setPersonStatus(CommonSysConstant.CODE_ONE);
            if( ObjectUtil.isNull(subInfoDO)){
                subInfoDO = new UserSubInfo();
                subInfoDO.setUserCode(userCode);
                userSubInfoDao.insertSelective(subInfoDO);
            }
            Long addDayLong = Long.parseLong(userExpireTimeLongDay)*24*3600*1000;
            if( StrUtil.isNotBlank(userExpireTimeLongDay) && Integer.parseInt(userExpireTimeLongDay)>0 ){
                Date expireDate = new Date(addDayLong + nowDateLong);
                if(subInfoDO.getUserExpireTime() != null){
                    expireDate = new Date(addDayLong + subInfoDO.getUserExpireTime().getTime());
                }
                subInfoDO.setUserExpireTime(expireDate);
                userSubInfoDao.updateByPrimaryKeySelective(subInfoDO);
            }
            userDao.updateByPrimaryKeySelective(userDO);
            personDao.updateByPrimaryKeySelective(personInfoDO);
            userMap.put("msg","审核成功！");

        }
    }

    @Override
    public void loginOut(String usertoken) {
        if (StrUtil.isNotBlank(usertoken)) {
            if(redisUtils.hasKey(usertoken)){
                redisUtils.del(usertoken);
            }
        }
    }

    //校验账号是否存在
    @Override
    public void checkUserCode(String userCode) {
        if (Validator.isEmpty(userCode)) {
            throw new ValidateException("账号不能为空!");
        }
        //查询在账号或手机号字段中是否存在数据
        int userNum = userDao.getRecordNumByMobile(userCode);
        if(userNum>0){
            throw new ValidateException("该账号已被注册!");
        }

    }

    //生成TOKEN
    private String genUserTokenKey(RequestInfo<ExterLoginQUERY> query, CoreUser userInfo, CorePersonInfo personInfo) {
        String usertoken = query.getBase().getUsertoken();
        if (StrUtil.isNotBlank(usertoken)) {
            if(redisUtils.hasKey(usertoken)){
                redisUtils.del(usertoken);
            }
        }
        //    (0群众 1保安 2警察,3超级管理员 4. 一级管理员  5.二级管理员)
        //TOCKEN前缀  TOKEN:DPTCODE:USERCODE:PERSONTYPE:随机数
        String personClassType = personInfo.getPersonClass();
//        String personFlag = "";
        switch (personClassType){
            case "0":
                personClassType = CommonSysConstant.PERSON_QZ_FLAG;
                break;
            case "1":
                personClassType = CommonSysConstant.PERSON_BA_FLAG;
                break;
            case "2":
                personClassType = CommonSysConstant.PERSON_JC_FLAG;
                break;
            case "3":
                personClassType = CommonSysConstant.PERSON_CJGLYFLAG;
                break;
            case "4":
                personClassType = CommonSysConstant.PERSON_GLY12_FLAG;
                break;
            case "5":
                personClassType = CommonSysConstant.PERSON_GLY12_FLAG;
                break;
            case "9":
                personClassType = CommonSysConstant.PERSON_YY_FLAG;
                break;
            default:
                personClassType = CommonSysConstant.PERSON_QT_FLAG;
        }

        if(personInfo.getPersonOrgCode() == null){
            personInfo.setPersonOrgCode(CommonSysConstant.UNKNOW_DPT_CODE);
        }
        StringBuilder tokenStr = new StringBuilder(CommonSysConstant.PERSON_TOKEN);
        tokenStr.append(CommonSysConstant.PERSON_TOKEN_SEP_CHAR);
        tokenStr.append(personInfo.getPersonOrgCode());
        tokenStr.append(CommonSysConstant.PERSON_TOKEN_SEP_CHAR);
        tokenStr.append(personClassType);
        tokenStr.append(CommonSysConstant.PERSON_TOKEN_SEP_CHAR);
        tokenStr.append(userInfo.getUserCode());
        return tokenStr.toString();
    }


    private void updateUserAndPersonDO(UpdateUserInfoQUERY reqBuss, final CorePersonInfo personInfo, final CoreUser userInfo) {
        if (ObjectUtil.isNull(userInfo) || ObjectUtil.isNull(personInfo)) {
            throw new ValidateException("获取用户人员信息失败!");
        }
        final String userCode = userInfo.getUserCode();
        int updateCount = 0;
        String reqParam = reqBuss.getUserRealName();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, userInfo.getUserRealName())) {
            userInfo.setUserRealName(reqParam);
            personInfo.setPersonRealName(reqParam);
            updateCount++;
        }
        String personCardNumber = reqBuss.getPersonCardNumber();
        if (StrUtil.isNotBlank(personCardNumber)) {
            personInfo.setPersonCardType("身份证");
            personInfo.setPersonCardNumber(personCardNumber);
            personInfo.setPersonSex(IdcardUtil.getGenderByIdCard(personCardNumber) + "");
            personInfo.setPersonBirthDate(IdcardUtil.getBirth(personCardNumber));
//            if (StrUtil.isNotBlank(personCardNumber) && IdcardUtil.isValidCard(personCardNumber)) {
//                personInfo.setPersonCardType("身份证");
//                personInfo.setPersonCardNumber(personCardNumber);
//                personInfo.setPersonSex(IdcardUtil.getGenderByIdCard(personCardNumber) + "");
//                personInfo.setPersonBirthDate(IdcardUtil.getBirth(personCardNumber));
//            } else {
//                personInfo.setPersonCardType(reqBuss.getPersonCardType());
//                personInfo.setPersonCardNumber(reqBuss.getPersonCardNumber());
//                personInfo.setPersonSex(reqBuss.getPersonSex());
//                personInfo.setPersonBirthDate(reqBuss.getPersonBirthDate());
//            }
            updateCount++;
        }
        reqParam = reqBuss.getPersonClass();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonClass())) {
//            String orgCode = TableCommonDataUtil.personClassToOrgCode(reqParam);
            String orgCode = CommonSysConstant.UNKNOW_DPT_CODE;
            personInfo.setPersonOrgCode(orgCode);
            personInfo.setPersonOrgName("未绑定！");
            personInfo.setPersonClass(reqParam);
            updateCount++;
        }

        reqParam = reqBuss.getPersondptName();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonCompanyCode())) {
            personInfo.setPersonCompanyCode(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonBirthAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonBirthAddress())) {
            personInfo.setPersonBirthAddress(reqParam);
            updateCount++;
        }

        reqParam = reqBuss.getPersonLiveAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonLiveAddress())) {
            personInfo.setPersonLiveAddress(reqParam);
            updateCount++;
        }

        reqParam = reqBuss.getPersonJobAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobAddress())) {
            personInfo.setPersonJobAddress(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonJobCardType();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobAddress())) {
            personInfo.setPersonJobAddress(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonJobCardNumber();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobCardNumber())) {
            personInfo.setPersonJobCardNumber(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonSecurityFlag();
        personInfo.setPersonSecurityFlag(reqParam);
        //有保安证
        if (CommonSysConstant.CODE_ONE.equals(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonSecurityFlag())) {
            personInfo.setPersonJobCardType("保安证");
            //调用第三方测试保安信息
            this.getSecurityDataFromThird(personInfo, personCardNumber);
        }
        reqParam = reqBuss.getPersonHeight();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonHeight())) {
            personInfo.setPersonJobCardNumber(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonNation();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonNation())) {
            personInfo.setPersonNation(reqParam);
            updateCount++;
        }
        reqParam = reqBuss.getPersonPolitics();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonPolitics())) {
            personInfo.setPersonPolitics(reqParam);
            updateCount++;
        }
        //修改姓名
        reqParam = reqBuss.getUserRealName();
        if(StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonPolitics())){
            userInfo.setUserRealName(reqParam);
            userInfo.setUserDisplayName(reqParam);
            personInfo.setPersonPolitics(reqParam);
            updateCount++;
        }

        //保存证件照片
        List<SecuriterCardInfoDATA> imageses = reqBuss.getImageses();
        if (ObjectUtil.isNotNull(imageses) && !imageses.isEmpty()) {
            for (SecuriterCardInfoDATA image : imageses) {
                CoreCardInfoWithBLOBs cardInfo = new CoreCardInfoWithBLOBs();
                cardInfo.setPersonCode(personInfo.getPersonCode());
                cardInfo.setCardStatus(CommonSysConstant.CODE_ONE);
                cardInfo.setCardImgType(image.getImgType());
                cardInfo.setCardImgFront(image.getImgContentFront());
                cardInfo.setCardImgReverse(image.getImgContentReverse());
                cardDao.updateOldRecordByPersonCode(cardInfo);
                TableCommonDataUtil.dealCrtUpdTableField(userCode, cardInfo);
                cardDao.insertSelective(cardInfo);
            }
            this.updateSecurityDataToThird(personInfo, imageses);
        }

        if (updateCount > 0) {
            TableCommonDataUtil.dealCrtUpdTableField(userCode, userInfo, personInfo);
            userDao.updateByPrimaryKeySelective(userInfo);
            personDao.updateByPrimaryKeySelective(personInfo);
        }

    }


    private void updateUserAndPersonDO(UpdateUserQUERY reqBuss, final CorePersonInfo personInfo, final CoreUser userInfo) {
        if (ObjectUtil.isNull(userInfo) || ObjectUtil.isNull(personInfo)) {
            throw new ValidateException("获取用户人员信息失败!");
        }
        final String userCode = userInfo.getUserCode();
        String reqParam = reqBuss.getUserRealName();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, userInfo.getUserRealName())) {
            userInfo.setUserRealName(reqParam);
            personInfo.setPersonRealName(reqParam);
        }
        String personCardNumber = reqBuss.getPersonCardNumber();
        if (StrUtil.isNotBlank(personCardNumber)) {
            personInfo.setPersonCardType("身份证");
            personInfo.setPersonCardNumber(personCardNumber);
            personInfo.setPersonSex(IdcardUtil.getGenderByIdCard(personCardNumber) + "");
            personInfo.setPersonBirthDate(IdcardUtil.getBirth(personCardNumber));
        }

        reqParam = reqBuss.getPersondptName();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonCompanyCode())) {
            personInfo.setPersonCompanyCode(reqParam);
        }

        reqParam = reqBuss.getPersonLiveAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonLiveAddress())) {
            personInfo.setPersonLiveAddress(reqParam);
        }

        reqParam = reqBuss.getPersonJobAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobAddress())) {
            personInfo.setPersonJobAddress(reqParam);
        }
        reqParam = reqBuss.getPersondptName();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonCompanyCode())) {
            personInfo.setPersonCompanyCode(reqParam);
        }
        reqParam = reqBuss.getPersonOrgCode();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonOrgCode())) {
            List<CoreDptInfo> dptInfoList = dptInfoDao.queryByDptCode(reqParam);
            if(dptInfoList.isEmpty() || dptInfoList.size()>1){
                throw new ValidateException("查询用户归属机构信息失败！");
            }
            personInfo.setPersonOrgCode(dptInfoList.get(0).getDptCode());
            personInfo.setPersonOrgName(dptInfoList.get(0).getDptName());
        }
        reqParam = reqBuss.getPersonJobAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobAddress())) {
            personInfo.setPersonJobAddress(reqParam);
        }
        reqParam = reqBuss.getPersonJobAddress();
        if (StrUtil.isNotBlank(reqParam) && !StrUtil.equals(reqParam, personInfo.getPersonJobAddress())) {
            personInfo.setPersonJobAddress(reqParam);
        }
        reqParam = reqBuss.getUserPhotoUrl();
        if (StrUtil.isNotBlank(reqParam)) {
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userInfo.getUserCode());
            if(userSubInfoDO != null ){
                userSubInfoDO.setUserPhotoUrl(reqParam);
                userSubInfoDao.updateByPrimaryKey(userSubInfoDO);
            }else {
                userSubInfoDO = new UserSubInfo();
                userSubInfoDO.setUserCode(userCode);
                userSubInfoDO.setUserPhotoUrl(reqBuss.getUserPhotoUrl());
                userSubInfoDao.insert(userSubInfoDO);
            }
        }
    }

    /* *
     * @describe:  类型描述 依据用户信息获取人员信息
     * @author shaofeng.cheng
     * @title getPersonInfoByUserInfoList
     * @date 2020/4/20 21:26
     * @param [userInfoList]
     * @return com.linkage.usercenter.pojo.entity.CorePersonInfo
     * @version: V1.0
     */
    private CorePersonInfo getPersonInfoByUserInfoList(List<CoreUser> userInfoList) {
        if (ObjectUtil.isNull(userInfoList)) {
            throw new ValidateException("获取不到用户信息！");
        }
        if (userInfoList.size() > 1) {
            throw new ValidateException("获取到多个用户信息！");
        }
        String personCode = userInfoList.get(0).getUserPersonCode();
        if (StrUtil.isBlank(personCode)) {
            throw new ValidateException("用户人员信息编码为空！");
        }
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(personCode);
        if (ObjectUtil.isNull(personInfo)) {
            throw new ValidateException("获取人员信息失败！");
        }
        return personInfo;
    }

    /* *
     * @describe:  类型描述 用户信息转VO
     * @author shaofeng.cheng
     * @title coreDataToUserInfoVO
     * @date 2020/4/20 17:17
     * @param [bussVO, userInfo, personInfo]
     * @return void
     * @version: V1.0
     */
    private void coreDataToUserInfoVO(final UserInfoVO bussVO, CoreUser userInfo, CorePersonInfo personInfo) {
        bussVO.setUserRealName(userInfo.getUserRealName());
        bussVO.setUserDisplayName(userInfo.getUserDisplayName());
        bussVO.setUserMobile(userInfo.getUserMobile());
        bussVO.setPersonCardType(personInfo.getPersonCardType());
        bussVO.setPersonCardNumber(personInfo.getPersonCardNumber());
        bussVO.setPersonSex(personInfo.getPersonSex());
        bussVO.setPersonBirthDate(personInfo.getPersonBirthDate());
        bussVO.setPersonClass(personInfo.getPersonClass());
        bussVO.setPersonBirthAddress(personInfo.getPersonBirthAddress());
        bussVO.setPersonLiveAddress(personInfo.getPersonLiveAddress());
        bussVO.setPersonJobAddress(personInfo.getPersonJobAddress());
        bussVO.setPersonJobCardType(personInfo.getPersonJobCardType());
        bussVO.setPersonJobCardNumber(personInfo.getPersonJobCardNumber());
        bussVO.setPersondptName(personInfo.getPersonCompanyCode());
        UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userInfo.getUserCode());
        if(userSubInfoDO != null){
            bussVO.setUserEmail(userSubInfoDO.getUserEmail());
            bussVO.setUserPhotoUrl(userSubInfoDO.getUserPhotoUrl());
            bussVO.setUserExpireTime(DateUtil.format(userSubInfoDO.getUserExpireTime(),
                    "yyyy-MM-dd HH:mm:ss"));
        }

    }

    /* *
     * @describe:  类型描述 数据处理
     * @author shaofeng.cheng
     * @title dealDataFrom
     * @date 2020/4/19 23:23
     * @param [reqBuss, userInfo, personInfo]
     * @return void
     * @version: V1.0
     */
    private void dealDataFrom(RegisterQUERY reqBuss, CoreUser userInfo, CorePersonInfo personInfo) {
        //1 userInfo
        String realName = reqBuss.getUserRealName();
        if (StrUtil.isNotBlank(realName) && StrUtil.isBlank(reqBuss.getUserDisplayName())) {
            reqBuss.setUserDisplayName(realName);
        }
        userInfo.setUserPassword(reqBuss.getUserPassword());
        userInfo.setUserRealName(realName);
        userInfo.setUserDisplayName(reqBuss.getUserDisplayName());
        userInfo.setUserMobile(reqBuss.getUserMobile());
        userInfo.setUserDelFlag(CommonSysConstant.CODE_ZERO);
        userInfo.setUserJobFlag(CommonSysConstant.CODE_ZERO);
        userInfo.setUserStatus(CommonSysConstant.CODE_ONE);

        String personClass = reqBuss.getPersonClass();
//        String orgCode = TableCommonDataUtil.personClassToOrgCode(personClass);
        // 公司名称
        personInfo.setPersonCompanyCode(reqBuss.getPersondptName());
        //2 personInfo
        personInfo.setPersonClass(personClass);
        personInfo.setPersonRealName(realName);
        String personCardNumber = reqBuss.getPersonCardNumber();
        personInfo.setPersonCode(userInfo.getUserCode());
        personInfo.setPersonCardType("身份证");
        personInfo.setPersonCardNumber(personCardNumber);
        personInfo.setPersonSex(IdcardUtil.getGenderByIdCard(personCardNumber) + "");
        personInfo.setPersonBirthDate(IdcardUtil.getBirth(personCardNumber));
//        //身份证校验
//        if (StrUtil.isNotBlank(personCardNumber) && IdcardUtil.isValidCard(personCardNumber)) {
//            personInfo.setPersonCode(personCardNumber);
//            personInfo.setPersonCardType("身份证");
//            personInfo.setPersonCardNumber(personCardNumber);
//            personInfo.setPersonSex(IdcardUtil.getGenderByIdCard(personCardNumber) + "");
//            personInfo.setPersonBirthDate(IdcardUtil.getBirth(personCardNumber));
//
//        } else {
//            personInfo.setPersonCode(IdUtil.randomUUID());
//            String cardType = reqBuss.getPersonCardType();
//            if (StrUtil.isBlank(cardType)) {
//                personInfo.setPersonCardType("身份证");
//            }
//            personInfo.setPersonCardNumber(reqBuss.getPersonCardNumber());
//            personInfo.setPersonSex(reqBuss.getPersonSex());
//            personInfo.setPersonBirthDate(reqBuss.getPersonBirthDate());
//        }
        personInfo.setPersonJobCardType(reqBuss.getPersonJobCardType());
        personInfo.setPersonSecurityFlag(reqBuss.getPersonSecurityFlag());
        personInfo.setPersonHeight(reqBuss.getPersonHeight());
        personInfo.setPersonNation(reqBuss.getPersonNation());
        personInfo.setPersonPolitics(reqBuss.getPersonPolitics());
        personInfo.setPersonBirthAddress(reqBuss.getPersonBirthAddress());
        personInfo.setPersonLiveAddress(reqBuss.getPersonLiveAddress());
        personInfo.setPersonJobAddress(reqBuss.getPersonJobAddress());
        personInfo.setPersonJobCardNumber(reqBuss.getPersonJobCardNumber());
        personInfo.setPersonMobile(reqBuss.getUserMobile());
        personInfo.setPersonOrgCode(CommonSysConstant.UNKNOW_DPT_CODE);
        personInfo.setPersonOrgName(CommonSysConstant.UNKNOW_DPT_NAME);
        if(StrUtil.isNotBlank(reqBuss.getPersonOrgCode())){
            personInfo.setPersonOrgCode(reqBuss.getPersonOrgCode());
            personInfo.setPersonOrgName(reqBuss.getPersonOrgName());
        }
        personInfo.setPersonDelFlag(CommonSysConstant.CODE_ZERO);
        personInfo.setPersonJobFlag(CommonSysConstant.CODE_TWO);
        personInfo.setPersonStatus(CommonSysConstant.CODE_ONE);
        //有保安证
        if (CommonSysConstant.CODE_ONE.equals(reqBuss.getPersonSecurityFlag())) {
            //调用第三方测试保安信息
            this.getSecurityDataFromThird(personInfo, personCardNumber);
        }

        //3 数据关联
        userInfo.setUserPersonCode(personInfo.getPersonCode());

        //设置保安未审核 人员类别  (0群众 1保安 2警察)
        if(CommonSysConstant.CODE_ONE.equals(personClass)){
            personInfo.setPersonJobFlag(CommonSysConstant.CODE_TWO);
            userInfo.setUserJobFlag(CommonSysConstant.CODE_TWO);
        }
        //保存证件照片
        List<SecuriterCardInfoDATA> imageses = reqBuss.getImageses();
        if (ObjectUtil.isNotNull(imageses) && !imageses.isEmpty()) {
            for (SecuriterCardInfoDATA image : imageses) {
                CoreCardInfoWithBLOBs cardInfo = new CoreCardInfoWithBLOBs();
                cardInfo.setPersonCode(personInfo.getPersonCode());
                cardInfo.setCardStatus(CommonSysConstant.CODE_ONE);
                cardInfo.setCardImgType(image.getImgType());
                cardInfo.setCardImgFront(image.getImgContentFront());
                cardInfo.setCardImgReverse(image.getImgContentReverse());
                TableCommonDataUtil.dealCrtUpdTableField(userInfo.getUserCode(), cardInfo);
                cardDao.insertSelective(cardInfo);
            }

        }
        this.updateSecurityDataToThird(personInfo, imageses);
    }

    /**
     * 调用第三方 上传保安信息
     *
     * @param personInfo
     * @param imageses
     */
    private void updateSecurityDataToThird(CorePersonInfo personInfo, List<SecuriterCardInfoDATA> imageses) {
        try {
            if (StrUtil.equals(CommonSysConstant.CODE_ONE, personInfo.getPersonSecurityFlag())) {
                if (ObjectUtil.isNull(imageses) || imageses.isEmpty()) {
                    logger.error("保安证照片和身份证照片未传！无法调用第三方上传保安信息----{}", personInfo.getPersonMobile());
                    return;
                }
                JSONObject securiterDTO = new JSONObject();
                securiterDTO.set("Name", personInfo.getPersonRealName());
                securiterDTO.set("COMPANYCODE", personInfo.getPersonCompanyCode());
                securiterDTO.set("IDCARDNO", personInfo.getPersonCardNumber());
                securiterDTO.set("TELEPHONE", personInfo.getPersonMobile());
                securiterDTO.set("SEX", personInfo.getPersonSex());
                securiterDTO.set("HEIGHT", personInfo.getPersonHeight());
                securiterDTO.set("BIRTHDATE", DateUtil.format(DateUtil.parse(personInfo.getPersonBirthDate(), "yyyyMMdd"), "yyyy-MM-dd"));
                securiterDTO.set("POLITICS", personInfo.getPersonPolitics());
                securiterDTO.set("NATION", personInfo.getPersonNation());
                securiterDTO.set("REGADDRESS", personInfo.getPersonBirthAddress());
                securiterDTO.set("NOWADDRESS", personInfo.getPersonLiveAddress());
                securiterDTO.set("SECURITYCODE", personInfo.getPersonJobCardNumber());
                List<JSONObject> imagesesList = new ArrayList<JSONObject>();
                for (SecuriterCardInfoDATA imagese : imageses) {
                    if (ObjectUtil.isNull(imagese)) {
                        continue;
                    }
                    JSONObject imageseDTO = new JSONObject();
                    imageseDTO.set("ImgType", imagese.getImgType());
                    imageseDTO.set("ImgContent", imagese.getImgContentFront());
                    imagesesList.add(imageseDTO);
                }
                if (ObjectUtil.isNull(imagesesList) || imagesesList.isEmpty()) {
                    logger.error("保安证照片和身份证照片未传！无法调用第三方上传保安信息----{}", personInfo.getPersonMobile());
                    return;
                }
                securiterDTO.set("Imageses", imagesesList);
                logger.info("调用第三方上传保安相关信息，入参：【{}】", JSONUtil.toJsonStr(securiterDTO));
                long bgTime = System.currentTimeMillis();
                String jsonRespString = homeManageFeign.saveSecurityGuardInfo(JSONUtil.toJsonStr(securiterDTO));
                logger.info("调用第三方上传保安相关信息，反参：【{}】 耗时：{}ms",
                        jsonRespString, ( System.currentTimeMillis() - bgTime)+"");
//            {"code":"0001","msg":"信息不完整[NATION 字段是必需的。; BIRTHDATE 字段是必需的。; POLITICS 字段是必需的。; HEIGHT 字段是必需的。]。"}
                if (StrUtil.isBlank(jsonRespString)) {
                    logger.error("调用第三方上传保安信息失败！");
                    return;
                }
                JSONObject jsonRespDTO = JSONUtil.parseObj(jsonRespString);
                logger.info("调用第三方上传保安信息成功----返回信息{}", jsonRespDTO);
                if (ObjectUtil.isNotNull(jsonRespDTO)) {
                    if (StrUtil.equals(CommonSysConstant.THIRD_SUCCESS_CODE, (String) jsonRespDTO.get("code"))) {
                        return;
                    } else {
                        throw new ValidateException((String) jsonRespDTO.get("msg"));
                    }
                }
            }

        } catch (Exception e) {
            logger.error("调用第三方上传保安信息失败----{}", e.getMessage());
            logger.error("调用第三方上传保安信息失败----{}", personInfo.getPersonMobile());
        }
    }

    /**
     * 通过第三方 获取保安信息 公司名称和证件号
     *
     * @param personInfo
     * @param personCardNumber
     */
    private void getSecurityDataFromThird(CorePersonInfo personInfo, String personCardNumber) {
        try {
            logger.info("调用第三方获取有证保安相关信息，入参：【{}】", personCardNumber);
            long bgTime = System.currentTimeMillis();
            String jsonRespString = homeManageFeign.getSecurityGuardInfo(personCardNumber);
            logger.info("调用第三方获取有证保安相关信息，反参：【{}】 耗时：{}ms",
                    jsonRespString, ( System.currentTimeMillis() - bgTime)+"");
            if(StrUtil.isBlank(jsonRespString)){
                logger.error("调用第三方获取有证保安相关信息出错！");
                return;
            }
            RespAppVO<JSONObject> voRespObj = JSONUtil.toBean(jsonRespString, RespAppVO.class);
            if (StrUtil.equals(CommonSysConstant.THIRD_SUCCESS_CODE, voRespObj.getCode())) {
                JSONObject dataObj = voRespObj.getData();
                String companyName = (String) dataObj.get("name");
                String securitycardid = (String) dataObj.get("securitycardid");
                personInfo.setPersonJobCardType("保安证");
                personInfo.setPersonJobCardNumber(securitycardid);
                //目前存储公司名称
                personInfo.setPersonCompanyCode(companyName);
            } else {
                personInfo.setPersonSecurityFlag(CommonSysConstant.CODE_ZERO);
            }
        }catch (Exception e){
            logger.error("调用第三方获取有证保安相关信息失败！", e);
        }

    }

    /**
     * 查询最新的位置信息
     * @param userCode
     * @return
     */
    private String queryNewestLocation(String userCode,String dptCode){
        Set<String> keySet = redisUtils.keys("location:"+dptCode+":"+userCode+":*");
        if(ObjectUtil.isNotEmpty(keySet)){
            Long timestamp = keySet.stream().mapToLong(x -> Long.parseLong(x.split(":")[3])).max().getAsLong();
            String key = "location:"+dptCode+":"+userCode+":"+timestamp;
            if(redisUtils.hasKey(key)){
                return String.valueOf(redisUtils.get(key));
            }
        }
        return null;
    }
}
